package com.jml.zlhq.app.adapter;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.jml.zlhq.app.AppConfig;
import com.jml.zlhq.app.AppContext;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.ui.CommonWebActivity;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.FileUtils;
import com.jml.zlhq.app.util.ImageUtils;
import com.jml.zlhq.app.util.StringUtil;
import com.jml.zlhq.app.util.UIUtil;
import com.jml.zlhq.app.widgets.CommonDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class HdDetailAdapter extends IBaseAdapter {
	private List<JSONObject> itemList;
	private AppContext appContext;
	private Activity activity;
	private String id;

	public HdDetailAdapter(Activity activity, List<JSONObject> itemList,String id) {
		this.itemList = itemList;
		this.appContext = (AppContext) activity.getApplication();
		this.activity = activity;
		this.id = id;
	}

	@Override
	public int getCount() {
		int count = itemList == null ? 0 : itemList.size();
		return count;
	}

	@Override
	public Object getItem(int position) {
		return itemList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
	
	@Override
	public View getView(int position, View convertView, final ViewGroup parent) {
		convertView = createItem(position, convertView, parent);
		return convertView;
	}
	
	static class ItemHolder {
		public ImageView ewm;
		public TextView tip,stepno,info;
		public LinearLayout  all,imgs,links;
		public View tipline;
	}
	private View createItem(int position, View convertView, final ViewGroup parent){
		ItemHolder holder = null;
		if(convertView==null){
			holder = new ItemHolder();
			int main_tandian_item = R.layout.hd_detail_item;
			convertView = LayoutInflater.from(appContext).inflate(main_tandian_item, null);
			holder.ewm = (ImageView) convertView.findViewById(R.id.hddetail_item_stepewm);
//			int height = (UIUtil.winWidth-UIUtil.dip2px(appContext, 20))*300/600;
//			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, height);
//			holder.ewm.setLayoutParams(lp);
			holder.tip = (TextView) convertView.findViewById(R.id.hddetail_item_tip);
			holder.tipline = convertView.findViewById(R.id.hddetail_item_tip_line);
			holder.stepno = (TextView) convertView.findViewById(R.id.hddetail_item_stepno);
			holder.info = (TextView) convertView.findViewById(R.id.hddetail_item_stepinfo);
			holder.all = (LinearLayout) convertView.findViewById(R.id.hddetail_item_all);
			holder.imgs = (LinearLayout) convertView.findViewById(R.id.hddetail_item_stepimgs);
			holder.links = (LinearLayout) convertView.findViewById(R.id.hddetail_item_steplinks);
			convertView.setTag(holder);
		}else{
			holder = (ItemHolder) convertView.getTag();
		}
		final JSONObject json = itemList.get(position);
		try {
			holder.all.setBackgroundColor(activity.getResources().getColor(position%2==0?R.color.color_f3:R.color.white));
			holder.tip.setVisibility(position==0?View.VISIBLE:View.GONE);
			holder.tipline.setVisibility(position==0?View.VISIBLE:View.GONE);
			holder.stepno.setText(Html.fromHtml("第"+(position+1)+"步&nbsp;&nbsp;&nbsp;&nbsp;"+"<font color='#333333'>"+BaseTools.getFrom("title", json)+"</font>"));
			String infoStr = BaseTools.getFrom("desc", json);
			infoStr = infoStr.replaceAll("</br>", "<br>");
			infoStr = infoStr.replaceAll("<br/>", "<br>");
			holder.info.setText(Html.fromHtml(infoStr));
			final String weixin = BaseTools.getFrom("codeList.0.codeImg", json);
			if(!StringUtil.isEmpty(weixin)){
				holder.ewm.setVisibility(View.VISIBLE);
				ImageLoader.getInstance().displayImage(URLs.IMAGE_HOST+weixin+"_scal_720x720.jpg", holder.ewm, UIUtil.getImageLoaderDisplayOptions(R.drawable.icon_default_z));
			}else{
				holder.ewm.setVisibility(View.GONE);
			}
			holder.ewm.setOnLongClickListener(holder.ewm.getVisibility()!=View.VISIBLE?null:new OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					ImageLoader.getInstance().loadImage(URLs.IMAGE_HOST+weixin+"_scal_720x720.jpg", new ImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {}
						@Override
						public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
							UIUtil.ToastMessage(activity, "加载二维码信息失败");
						}
						@Override
						public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
							try {
								String ewm = FileUtils.getSDRoot(AppConfig.APP_EWM+"/二维码_"+id+".jpg");
								ImageUtils.saveImageToSD(activity, ewm, loadedImage, 100);
								final CommonDialog show = new CommonDialog(activity, true);
								show.show(true, true, false, "二维码已保存", "二维码已经成功保存到:SD卡/"+AppConfig.APP_ROOT+"/二维码/二维码_"+id+".jpg"+",请打开微信扫一扫，点击右上角(三点)->从相册选择二维码", "确定", "", new OnClickListener(){
									@Override
									public void onClick(View v) {
										show.dismiss();
									}
								}, null);
							} catch (Exception e) {
								UIUtil.ToastMessage(activity, "加载二维码信息失败");
							}
						}
						@Override
						public void onLoadingCancelled(String imageUri, View view) {}
					});
					return true;
				}
			});
			JSONArray imgsArr = json.getJSONArray("imageList");
			holder.imgs.removeAllViewsInLayout();
			for (int i = 0; imgsArr!=null && i < imgsArr.length(); i++) {
				ImageView img = new ImageView(activity);
				img.setScaleType(ScaleType.FIT_CENTER);
				ImageLoader.getInstance().displayImage(URLs.IMAGE_HOST+BaseTools.getFrom("imageList."+i+".imageUrl", json)+"_scal_720x720.jpg", img, UIUtil.getImageLoaderDisplayOptions(R.drawable.icon_default_f),new ImageLoadingListener() {
					
					@Override
					public void onLoadingStarted(String imageUri, View view) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
						LinearLayout.LayoutParams mlp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,(int)(loadedImage.getHeight()*1.6));
						mlp.setMargins(0, 0, 0, UIUtil.dip2px(activity, 5));
						((ImageView)view).setScaleType(ScaleType.FIT_CENTER);
						((ImageView)view).setLayoutParams(mlp);
						((ImageView)view).setImageBitmap(loadedImage);
					}
					
					@Override
					public void onLoadingCancelled(String imageUri, View view) {
						// TODO Auto-generated method stub
						
					}
				});
				holder.imgs.addView(img);
			}
			JSONArray linksArr = json.getJSONArray("linkList");
			holder.links.removeAllViewsInLayout();
			for (int i = 0; linksArr!=null && i < linksArr.length(); i++) {
				TextView img = new TextView(activity);
				LinearLayout.LayoutParams mlp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
				mlp.setMargins(0, UIUtil.dip2px(activity, 7), 0, 0);
				img.setLayoutParams(mlp);
				img.setPadding(0, UIUtil.dip2px(activity, 5), 0, UIUtil.dip2px(activity, 5));
				img.setTextColor(activity.getResources().getColor(R.color.white));
				img.setTextSize(13);
				img.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.fillet_e95847));
				img.setGravity(Gravity.CENTER);
				img.setText(BaseTools.getFrom("linkList."+i+".linkName", json));
				img.setTag(i);
				img.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						/*Intent intent = new Intent();       
					    intent.setAction("android.intent.action.VIEW");   
					    Uri content_url = Uri.parse(BaseTools.getFrom("linkList."+v.getTag()+".linkUrl", json));  
					    intent.setData(content_url); 
					    activity.startActivity(intent);*/
					    Bundle data = new Bundle();
						data.putString("title", "赚零花钱");
						data.putString("url", BaseTools.getFrom("linkList."+v.getTag()+".linkUrl", json));
						UIUtil.openActivity(activity, CommonWebActivity.class, data);
					}
				});
				holder.links.addView(img);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return convertView;
	}
}
